<?php
/**
 * Created by PhpStorm.
 * User: asus
 * Date: 2019/7/29
 * Time: 17:45
 */

namespace App\Http\Traits;

use App\Services\ResponseCode;
use Symfony\Component\HttpFoundation\Response as FoundationResponse;

trait ApiResponse
{
    public function response($message = null, $data = [], $code = ResponseCode::SUCCESS, $header = [])
    {
        if ($message) {
            $return['message'] = $message;
        }

        // 仅在业务处理成功的情况返回data字段
        if ($code === ResponseCode::SUCCESS) {
            $return['data'] = $data;
        }

        $return['code'] = $code;
        if (config('api.api_encrypt_enable') === true && !in_array(request()->path(), config('api.api_encrypt_exclude_paths'))) {
            $return = ['encrypted' => openssl_encrypt(json_encode($return), config('api.api_encrypt_algo'), config('api.api_encrypt_passphrase'), 0, config('api.api_encrypt_iv'))];
        }
        return response($return, 200, $header);
    }

    public function success($message, $data = [])
    {
        $data = $this->nullToString($data);

        return $this->response($message, $data);
    }

    public function created($message, $data = [])
    {
        $data = $this->nullToString($data);

        return $this->response($message, $data, FoundationResponse::HTTP_CREATED);
    }

    public function errorBadRequest($message, $data = [], $code = FoundationResponse::HTTP_BAD_REQUEST)
    {
        $data = $this->nullToString($data);

        return $this->response($message, $data, $code);
    }

    /*
     * 递归转换null为string
     * */
    private function nullToString(&$source)
    {
        foreach ($source as &$v) {
            if ($v === null) {
                $v = '';
            } elseif (is_array($v) || is_object($v)) {
                if (method_exists($v, 'toArray')) {
                    $v = $v->toArray();
                }
                if (method_exists($v, 'toJson')) {
                    $v = json_decode($v->toJson(), true);
                }
                $v = $this->nullToString($v);
            }
        }
        return $source;
    }
}
